package com.learn.demo.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * websocket示例
 */
public class MyWebSocketDemoServer {
    private int port;

    public MyWebSocketDemoServer(int port) {
        this.port = port;
    }
    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //使用HTTP的编码解码器
                            pipeline.addLast(new HttpServerCodec());
                            //以块方式写
                            pipeline.addLast(new ChunkedWriteHandler());
                            /**
                             * 1.http数据在传输过程中是分段的，HttpObjectAggregator可以将多个段聚合起来
                             * 2.当浏览器发送大量数据时，会发送多次HTTP请求
                             */
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            /**
                             * 1.对应WebSocket，它的数据是以帧传递的
                             * 2.WebSocketServerProtocolHandler的核心功能是将HTTP协议升级为ws协议，保持长连接
                             * 3.连接方式为 ws://localhost:port/myWebsocketDemo
                             */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/myWebsocketDemo"));
                            //自定义handler处理业务逻辑
                            pipeline.addLast(new MyTextWebSocketDemoServerFrameHandler());
                        }
                    });
            //启动服务器
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            System.out.println("服务器已启动...");
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new MyWebSocketDemoServer(6767).run();
    }
}
